//  
var createError = require('http-errors');
// express框架
var express = require('express');
// node 自带的path模块 路径
var path = require('path');
// 获取cookie信息进行转换 
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 首页路由
var indexRouter = require('./routes/index');
// 用户模块的路由设置
var usersRouter = require('./routes/users');
// 加载用户商品路由
var goods = require('./routes/goods')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 登录拦截
app.use((req,res,next)=>{
  //判断是否登录，若已登录则继续执行
  if(req.cookies.userId) {
    next()
  } else {
    // 设置未登录时允许访问的接口（未登录时的权限）
    // req.originalUrl.indexOf('/goods/list') 可以替换为 req.path == '/goods/list'
    if(req.originalUrl == '/users/login' || req.originalUrl == '/users/logout' || req.originalUrl.indexOf('/goods/list') > -1) {
      next()
    } else {
      res.json({
        status: '10001',
        msg: '当前未登录',
        result: ''
      })
    }
  }
})
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goods);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
